import json
import re
import requests

def convert_alias_to_name(alias):
    """将菜单别名转换为路由名称"""
    if not alias:
        return ""

    if '.' in alias:
        parts = alias.split('.')[1:]  # 去掉system前缀
        result = []
        for part in parts:
            # 处理下划线和驼峰转换
            words = part.split('_')
            camel_case = words[0] + ''.join(word.capitalize() for word in words[1:])
            result.append(camel_case.replace('_', ''))
        return ''.join(result)

    # 处理普通下划线命名
    words = alias.split('_')
    return words[0] + ''.join(word.capitalize() for word in words[1:]).replace('_', '')

def process_menu(menu, parent_path=''):
    """递归处理菜单项"""
    if menu.get('enableMenu', 0) != 1:
        return None

    # 处理路径
    current_path = menu.get('menuUrl', '').strip()
    if not current_path:
        current_path = '/'  # 提供一个默认路径

    # 处理组件路径
    component_path = ''
    if menu.get('templateUrl'):
        component_path = re.sub(r'^bms/views/', '', menu['templateUrl'].replace('.html', ''))
        if not component_path:
            component_path = 'Layout'  # 提供一个默认值

    # 解析load字段
    file_js = []
    if menu.get('load'):
        try:
            load_str = menu.get('load', '').strip()
            if not load_str:
                print("load字段为空")
                return None

            # 清理字符串使其符合JSON格式
            load_str = (load_str.strip()
                        .replace("'", '"')
                        .replace(' ', '')
                        .replace(r'\n', '')
                        .replace(r'\r', ''))
            load_str = re.sub(r'(\w+):', r'"\1":', load_str)  # 将键加上双引号
            load_str = re.sub(r',\s*([}\]])', r'\1', load_str)  # 清理多余的逗号

            load_config = json.loads(load_str)
            for item in load_config:
                if 'name' in item and 'files' in item:
                    for f in item['files']:
                        lower_file = f.lower()
                        if f.endswith('.js') and ('controller' in lower_file or 'ctrl' in lower_file):
                            file_js.append(f)
        except json.JSONDecodeError as e:
            print(f"JSON解析失败: {load_str}", e)
        except Exception as e:
            print(f"解析load字段失败: {menu.get('load')}", e)

    # 构建路由对象
    route = {
        "path": current_path or '/',
        "component": component_path or "Layout",
        "name": convert_alias_to_name(menu.get('alias')) or 'Unnamed',
        "meta": {
            "title": menu.get('name') or 'Untitled',
            "icon": menu.get('menuIcon') or 'el-icon-menu',
            "htmlUrl": menu.get('templateUrl') or ''
        }
    }

    # 添加js文件信息
    if file_js:
        route['meta']['fileJs'] = file_js

    # 处理子菜单
    children = []
    for child in menu.get('children', []):
        child_route = process_menu(child)
        if child_route:
            children.append(child_route)

    if children:
        route['children'] = children

    # 调整Layout路径
    if route['component'] == 'Layout' and 'children' in route:
        route['path'] = re.sub(r'/$', '', route['path'])

    return route if route.get('component') else None

def convert_angular_menu_to_ruoyi(angular_menu):
    """转换入口函数"""
    result_routes = []
    for top_menu in angular_menu:
        converted = process_menu(top_menu)
        if converted:
            result_routes.append(converted)
    return result_routes

def get_routers_and_save():
    """获取数据并保存到文件"""
    try:
        # 配置请求头
        headers = {
            "Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJKWkZXWV9hZG1pbi5iNzBhYmQyZC1hZTQ5LTRmNTAtODdiNC0yN2RkN2MwMzBhMjYiLCJ0ZW5hbnRJZCI6ImI3MGFiZDJkLWFlNDktNGY1MC04N2I0LTI3ZGQ3YzAzMGEyNiIsImV4cCI6MTc0ODQ4MjQ0OCwiaWF0IjoxNzQ4Mzk2MDQ4fQ.8XabJXRb9uxuGuGmfmnCad15Le-QgocxoOrXxnEbmO6KHu6i1-eN_wZ_iH59oGRwq3aZPV0mU-znuG4fw5_Npg",
            "tenant-id": "b70abd2d-ae49-4f50-87b4-27dd7c030a26"
        }
        response = requests.get(
            'http://uatbms.einyun.com/portal/sys/sysMenu/v1/getCurrentUserMenu',
            headers=headers,
            params={'menuAlias': 'system.front_menu'},
            timeout=10
        )
        response.raise_for_status()

        if response.status_code == 200:
            data = response.json()
            if data.get('state'):
                res_data = data.get('value', [])
                if res_data:
                    ruoyi_routes = convert_angular_menu_to_ruoyi(res_data)
                    # 写入文件
                    with open('data.json', 'w', encoding='utf-8') as f:
                        json.dump({"data": ruoyi_routes}, f, indent=2, ensure_ascii=False)
                    print("数据已成功写入data.json")
                    return

                # 空数据情况
                with open('data.json', 'w') as f:
                    json.dump({"data": []}, f)
            else:
                print("API返回状态异常")
        else:
            print(f"请求失败，状态码：{response.status_code}")

    except requests.exceptions.RequestException as e:
        print("请求失败:", str(e))
    except Exception as e:
        print("请求处理异常:", str(e))

if __name__ == "__main__":
    get_routers_and_save()
